﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace Web.Ajax.Data
{
	public class Object //: JsonObject
	{
		public long Id = -1;

		public virtual void Save()
		{
			Save(this);
		}

		public static Array Get(System.Type t)
		{
			Storage s = Storage.GetStorage(t);
			return s.Get();
		}

		public static T[] Get<T>()
		{
			return (T[])Get(typeof(T));
		}

		public static Object Get(System.Type t, long? id)
		{
			if (!id.HasValue || id.Value == -1)
				return null;
			Storage s = Storage.GetStorage(t);
			return s.Get(t, id.Value);
		}

		public static T Get<T>(long? id) where T : Object
		{
			return (T)Get(typeof(T), id);
		}

		public static object CheckContext(string key)
		{
			if (HttpContext.Current != null)
				return HttpContext.Current.Items[key];
			return null;
		}

		public static void SaveInContext(string key, object o)
		{
			if (HttpContext.Current != null)
				HttpContext.Current.Items[key] = o;
		}



		public static string GetString(object s)
		{
			if (s == null || s.ToString() == "null")
				return "";
			return (string)s;
		}

		public static int GetInt(object i)
		{
			try
			{
				return int.Parse((string)i);
			}
			catch { }
			return 0;
		}

		public static long GetLong(object l)
		{
			try
			{
				return long.Parse((string)l);
			}
			catch { }
			return 0;
		}

		public static decimal GetDecimal(object d)
		{
			try
			{
				return decimal.Parse((string)d);
			}
			catch { }
			return 0m;
		}

		public static void Save(Object o)
		{
			var t = o.GetType();
			var s = Storage.GetStorage(t);
			s.Save(o);
		}

		public static void Delete(System.Type t, long? Id)
		{
			var s = Storage.GetStorage(t);
			s.Delete(Id, null);
		}

		public static void Delete<T>(long? Id)
		{
			Delete(typeof(T), Id);
		}
	}
}
